<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/3/2 15:46
 * Remark:
 */

namespace App\Tools\DocxGenerator;

use App\Consts\DocConsts\DocConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\AppFunc;
use App\Func\CurlFunc;
use App\Func\PathFunc;
use App\Func\ResponseFunc;
use App\Func\SystemFunc;
use Illuminate\Http\Exceptions\HttpResponseException;
use JetBrains\PhpStorm\ArrayShape;

class FormatDocx
{
    #[ArrayShape(["oldPath" => "string", "newPath" => "array|string|string[]"])] public static function wordToHtml($inputFileAddress, $fileName): array|string
    {
        $fileNameArray= explode(".",$fileName);
        $newPath = str_replace($fileName,$fileNameArray[0].".html",$inputFileAddress);
        $oldPath= PathFunc::getDocxGenerator().$fileNameArray[0].".html"; //旧目录
        $res = CurlFunc::sendPost("http://127.0.0.1:8362/translateFileToHtml",[
            'fileUrl'=>$inputFileAddress,
            'savePath'=>$oldPath,
            'outputPath'=>$newPath,
        ]);
        $res = json_decode($res,true);
        dd($res);
        if(!$res["ok"]){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '合同预览转换中,请稍后再试。',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        return [
            "oldPath" => $oldPath,
            "newPath" => $newPath
        ];
    }

    #[ArrayShape(["oldPath" => "string", "newPath" => "array|string|string[]"])]
    public static function wordToPdf($inputFileAddress, $fileName): array|string
    {
        $fileNameArray= explode(".",$fileName);
        $newPath = str_replace($fileName,$fileNameArray[0].".pdf",$inputFileAddress);
        if(!is_dir(PathFunc::getDocxGenerator())){
            @mkdir(PathFunc::getDocxGenerator());
            (new SystemFunc())->setFileOwnerAndGroup(PathFunc::getDocxGenerator(),'www','www');
//            \chown(PathFunc::getDocxGenerator(), "www");
        }
//        $oldPath= PathFunc::getDocxGenerator().$fileNameArray[0].".pdf"; //旧目录
        $path = AppFunc::getNodeConfig()::NODE_WORD_TO_PDF;

        $oldPath= $path.$fileNameArray[0].".pdf"; //旧目录
        $res = CurlFunc::sendPost("http://127.0.0.1:8362/translateFileToPdf",[
            'fileUrl'=>storage_path("app").DIRECTORY_SEPARATOR.$inputFileAddress,
            'savePath'=>$oldPath,
            'outputPath'=>storage_path("app").DIRECTORY_SEPARATOR.(explode(".",$newPath)[0]).".pdf",
        ]);
        $res = json_decode($res,true);

        if(!$res["ok"]){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '合同预览转换中,请稍后再试。',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        return [
            "oldPath" => $oldPath,
            "newPath" => $newPath
        ];
    }

    /**
     * 模板替换
     * @param $templateDataJsonStr
     * @param $inputFileAddress
     * @param array $fileInfo
     * @return string
     */
//    public static function formatDockReplace($templateDataJsonStr, $inputFileAddress, array $fileInfo = []): string
//    {
//        $path = PathFunc::getStorageApp()."templateFormat".DIRECTORY_SEPARATOR;
//        $pathC = $path.date("Ymd",$fileInfo['create_at']).DIRECTORY_SEPARATOR;
//        if(!is_dir($pathC)){
//            mkdir($pathC);
//        }
//        $pathF = $pathC.md5($fileInfo['file_name'].$fileInfo['create_at'])."_format.".$fileInfo['file_ext'];
//        touch($pathF);
//        $res = CurlFunc::sendPost("http://192.168.4.216:8362/replaceTemplate",[
//            'templateDataJsonStr'=> $templateDataJsonStr,
//            'inputFileAddress'=>$inputFileAddress,
//            'outputFileAddress'=>$pathF
//        ]);
//        $res =  json_decode($res,true);
//        if(!$res["ok"]){
//            throw new HttpResponseException(ResponseFunc::returnJson(
//                'error',
//                null,
//                '创建格式合同失败',
//                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
//            ));
//        }
//
//        return $pathF;
//    }


    public static function formatClientEvaluationTemplateReplace($templateDataJsonStr, $inputFileAddress, array $fileInfo = []): string
    {
        # 预存文件地址
        $path = PathFunc::getStorageApp()."templateFormat".DIRECTORY_SEPARATOR;
        # 创建文件夹
        $pathC = $path.date("Ymd",$fileInfo['create_at']).DIRECTORY_SEPARATOR;

        if(!is_dir($pathC)){
            mkdir($pathC);
            // 修改文件夹操作人为www
            (new SystemFunc())->setFileOwnerAndGroup($pathC,'www','www');
//            \chown($pathC, "www");
        }
        # 保存的文件名称
        $fileNewName = $fileInfo['file_name'].".".$fileInfo['file_ext'];
        # 文件完整地址
        $pathF = $pathC.$fileNewName;
        # 创建文件
        # 删除历史文件
        @unlink($pathF);
        touch($pathF);
        # 替换文件关键词
        $res = CurlFunc::sendPost(DocConsts::DOC_REPLACE_URL,[
            'templateDataJsonStr'=> $templateDataJsonStr,
            'inputFileAddress'=>$inputFileAddress,
            'outputFileAddress'=>$pathF
        ]);
        $res =  json_decode($res,true);

        if(!$res["ok"]){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '生成调解函失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        # 返回文件名字
        return "templateFormat".DIRECTORY_SEPARATOR.date("Ymd",$fileInfo['create_at']).DIRECTORY_SEPARATOR.$fileNewName;
    }


    public static function formatDockReplace($templateDataJsonStr, $inputFileAddress, array $fileInfo = []): string
    {
        # 预存文件地址
        $path = PathFunc::getStorageApp()."file".DIRECTORY_SEPARATOR;
        # 创建文件夹
        $pathC = $path.date("Ymd",$fileInfo['create_at']).DIRECTORY_SEPARATOR;
        if(!is_dir($pathC)){
            mkdir($pathC);
            (new SystemFunc())->setFileOwnerAndGroup($pathC,'www','www');
//            \chown($pathC, "www");
        }
        # 保存的文件名称
        $fileNewName = $fileInfo['file_name'];
        # 文件完整地址
        $pathF = $pathC.$fileNewName;
        # 创建文件
        # 删除历史文件
        @unlink($pathF);
        touch($pathF);
        # 替换文件关键词
        $res = CurlFunc::sendPost(DocConsts::DOC_REPLACE_URL,[
            'templateDataJsonStr'=> $templateDataJsonStr,
            'inputFileAddress'=>$inputFileAddress,
            'outputFileAddress'=>$pathF
        ]);
        $res =  json_decode($res,true);

        if(!$res["ok"]){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '创建格式合同失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        # 返回文件名字
        return "file".DIRECTORY_SEPARATOR.date("Ymd",$fileInfo['create_at']).DIRECTORY_SEPARATOR.$fileNewName;
    }

}